<template>
  <div class="uploadimg">
    <div>
      <p>商品主图</p>
      <el-upload
        :limit="1"
        :action="actionUrl"
        :on-preview="handlePreview"
        :on-remove="handleRemoveOne"
        :on-exceed="handExceed"
        :file-list="mainfileList"
        :http-request="uploadFileImgOne"
        list-type="picture">
        <el-button :disabled="disableIinput" size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </div>
    <div>
      <p>视频封面</p>
      <el-upload
        :limit="1"
        :action="actionUrl"
        :on-preview="handlePreview"
        :on-remove="handleRemoveThree"
        :on-exceed="handExceed"
        :file-list="coverImg"
        :http-request="uploadFileImgThree"
        list-type="picture">
        <el-button :disabled="disableIinput" size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </div>
    <div>
      <p>主图视频</p>
      <div style="position: relative">
        <el-upload
          :action="uploadUrl"
          :show-file-list="false"
          :before-upload="beforeUploadVideo"
          :on-progress="uploadVideoProcess"
          :http-request="uploadFileVieo">
          <video v-if="showVideoPath !='' && videoFlag == false" :src="showVideoPath" class="avatar" controls="controls">您的浏览器不支持视频播放</video>
          <el-button v-else-if="showVideoPath =='' && videoFlag == false" :disabled="disableIinput" size="small" type="primary">点击上传</el-button>
          <!--<i v-else-if="showVideoPath =='' && videoFlag == false" class="el-icon-plus avatar-uploader-icon"></i>-->
          <el-progress v-if="videoFlag == true" :percentage="videoUploadPercent" type="circle" style="margin-top:30px;"/>
        </el-upload>
        <i v-if="showVideoPath !='' && videoFlag == false" class="el-icon-delete" @click="delmp4"/>
      </div>
      <p class="el-upload__tip">请保证视频格式正确，且不超过20M</p>
    </div>
    <div>
      <p>商品图片</p>
      <el-upload
        :action="actionUrl"
        :on-preview="handlePreview"
        :on-remove="handleRemoveTow"
        :file-list="fileList"
        :http-request="uploadFileImgTow"
        :on-exceed="handExceedTow"
        list-type="picture">
        <el-button :disabled="disableIinput" size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import * as commodity from '../../../api/commodity'
export default {
  /* eslint-disable vue/require-prop-types */
  props: ['type', 'editorData'],
  data() {
    return {
      actionUrl: '',
      disableIinput: false,
      mainfileList: [], // 主图
      fileList: [], // 详情图
      coverImg: [], // 封面图
      // 上传视频
      uploadUrl: '',
      videoFlag: false,
      videoUploadPercent: 0,
      showVideoPath: '' // 视频地址
    }
  },
  beforeMount() {
    if (this.type !== 1) {
      const objImg = {}
      objImg.url = this.editorData.defaultPicUrl
      this.mainfileList.push(objImg)
      this.getselectAllList()
      this.getImg()
    }
    if (this.type === 3) {
      this.disableIinput = true
    }
  },
  created() {
    this.fileList = []
    this.initUploadFileurl()
  },
  methods: {
    initUploadFileurl() {
      this.actionUrl = process.env.BASE_API + 'file/uploadImageAndCrtThumbImagesRichEdit'
      this.uploadUrl = process.env.BASE_API + 'file/uploadFiles'
    },
    getImg() {
      const param = {
        itemId: this.editorData.itemId,
        isDefault: 0
      }
      commodity.getImgList(param).then(res => {
        if (res.data.code !== 1) {
          this.$message.error(res.data.msg)
          return false
        }
        if (res.data.data === 'null' || res.data.data === null) {
          return false
        }
        const imgdata = res.data.data.records
        for (const i in imgdata) {
          const obj = {}
          obj.url = imgdata[i].picUrl
          this.fileList.push(obj)
        }
      })
    },
    getselectAllList() {
      const param = {
        itemId: this.editorData.itemId
      }
      commodity.getselectAllList(param).then(res => {
        if (res.data.code !== 1) {
          this.$message.error(res.data.msg)
          return false
        }
        if (res.data.data === 'null' || res.data.data === null) {
          return false
        }
        if (res.data.data.length <= 0) {
          return false
        }
        const objImg = {}
        objImg.url = res.data.data[0].picUrl
        this.coverImg.push(objImg)
        this.showVideoPath = res.data.data[0].videoUrl
      })
    },
    // 商品主图
    uploadFileImgOne(content) {
      const fd = new FormData()
      fd.append('images', content.file)
      fd.append('resPath', this.resPath)
      const fileSize = content.file.size < 512000
      if (!fileSize) {
        this.$message({
          message: '上传图片不能大于500kb',
          type: 'warning'
        })
      } else {
        const loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        axios.post(content.action, fd).then(res => {
          loading.close()
          if (res.data.code === 1) {
            const obj = {}
            obj.url = res.data.data[0].maxImageUrl
            this.mainfileList.push(obj)
            this.$message({
              message: '上传成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: 'warning'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'info',
            message: res.message
          })
          loading.close()
        })
      }
    },
    // 商品详情图
    uploadFileImgTow(content) {
      const fd = new FormData()
      fd.append('images', content.file)
      fd.append('resPath', this.resPath)
      const fileSize = content.file.size < 512000
      if (!fileSize) {
        this.$message({
          message: '上传图片不能大于500kb',
          type: 'warning'
        })
      } else {
        const loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        axios.post(content.action, fd).then(res => {
          loading.close()
          if (res.data.code === 1) {
            const obj = {}
            obj.url = res.data.data[0].maxImageUrl
            this.fileList.push(obj)
            this.$message({
              message: '上传成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: 'warning'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'info',
            message: res.message
          })
          loading.close()
        })
      }
    },
    // 视频封面
    uploadFileImgThree(content) {
      const fd = new FormData()
      fd.append('images', content.file)
      fd.append('resPath', this.resPath)
      const fileSize = content.file.size < 512000
      if (!fileSize) {
        this.$message({
          message: '上传图片不能大于500kb',
          type: 'warning'
        })
      } else {
        const loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        axios.post(content.action, fd).then(res => {
          loading.close()
          if (res.data.code === 1) {
            const obj = {}
            obj.url = res.data.data[0].maxImageUrl
            this.coverImg.push(obj)
            this.$message({
              message: '上传成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: 'warning'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'info',
            message: res.message
          })
          loading.close()
        })
      }
    },
    // 上传视频
    // 上传前回调
    beforeUploadVideo(file) {
      const isLt20M = file.size / 1024 / 1024 < 20
      if (['video/mp4'].indexOf(file.type) === -1) { // 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'
        this.$message.error('请上传正确的视频格式')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传视频大小不能超过20MB哦!')
        return false
      }
    },
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true
      this.videoUploadPercent = file.percentage.toFixed(0)
    },
    uploadFileVieo(content) {
      console.log('内容：')
      console.log(content)
      const fd = new FormData()
      fd.append('files', content.file)
      const loading = this.$loading({
        lock: true,
        text: '保存中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      axios({
        url: content.action,
        method: 'POST',
        // filePath: fd,
        headers: {
          'Content-Type': 'multipart/form-data'
        }, // this is important !
        contentType: false,
        processData: false,
        // name: 'files',
        data: fd,
        params: fd

      }).then(res => {
        loading.close()
        if (res.data.code === 1) {
          this.$message({
            message: '上传成功',
            type: 'success'
          })
          console.log(res.data.data)
          this.videoFlag = false
          this.videoUploadPercent = 0
          this.showVideoPath = this.HOSTURL + '' + res.data.data[0].filePath
        } else {
          this.$message({
            message: res.data.msg,
            type: 'warning'
          })
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('上传视频失败')
        loading.close()
      })
    },
    delmp4() {
      this.showVideoPath = ''
    },
    incrementTotal() {
      if (this.mainfileList.length <= 0) {
        this.$message.error('请上传主图')
        this.$emit('emitSuccess', 'noImg')
        return false
      } else if (this.fileList.length <= 0) {
        this.$message.error('请上传详情图')
        this.$emit('emitSuccess', 'noImg')
        return false
      } else {
        const fileList = []
        for (const val of this.fileList) {
          fileList.push(val.url)
        }
        let showVideoUrl = []
        if (this.coverImg.length > 0 || this.showVideoPath !== '') {
          const obj = {}
          obj.picUrl = this.coverImg[0].url
          obj.videoUrl = this.showVideoPath
          showVideoUrl.push(obj)
        } else {
          showVideoUrl = [{ picUrl: '', videoUrl: '' }]
        }
        this.$emit('emitSuccess', [this.mainfileList, showVideoUrl, fileList])
      }
    },
    handleRemoveOne(file, fileList) {
      var _this = this
      this.mainfileList.forEach(function(item, index) {
        if (file.uid === item.uid) {
          _this.mainfileList.splice(index, 1)
        }
      })
    },
    handleRemoveTow(file, fileList) {
      var _this = this
      this.fileList.forEach(function(item, index) {
        if (file.uid === item.uid) {
          _this.fileList.splice(index, 1)
        }
      })
    },
    handleRemoveThree(file, fileList) {
      var _this = this
      this.coverImg.forEach(function(item, index) {
        if (file.uid === item.uid) {
          _this.coverImg.splice(index, 1)
        }
      })
    },
    handExceed(files, fileList) {
      this.$message({
        message: '主图最多上传一张',
        type: 'warning'
      })
    },
    handExceedTow(files, fileList) {
      this.$message({
        message: '详情图最多上传5张',
        type: 'warning'
      })
    },
    handlePreview(file) {
      console.log(file)
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
  .uploadimg{
    padding: 20px 40px;
    .el-upload-list--picture .el-upload-list__item{
      width: 50%
    }
  }
  .avatar{
    width: 300px;
    height: 300px;
  }
  .el-icon-delete{
    position: absolute;
    left: 300px;
    bottom: 0;
    cursor: pointer;
  }
</style>
